package DaoImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import Dao.NoticeDao;
import Entity.Notice;
import Entity.Stclass;
import Util.HibernateUtil;

public class NoticeDaoImpl implements NoticeDao{
	//添加公告
	@Override
	public boolean insertNotice(Notice notice) {
		Transaction ts = null;
		try{
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			ts=session.beginTransaction();
			session.save(notice);
			ts.commit();
			return true;
		}catch(Exception e)
		{
			ts.rollback();
			e.printStackTrace();
            return false;
		}finally{
			if(ts!=null)
			{
				ts=null;
			}
		}
	}
	//删除公告
	@Override
	public boolean deleteNotice(Notice notice) {
		Transaction ts = null;
		try{
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			ts=session.beginTransaction();
			session.delete(notice);
			ts.commit();
			return true;
		}catch(Exception e)
		{
			ts.rollback();
			e.printStackTrace();
            return false;
		}finally{
			if(ts!=null)
			{
				ts=null;
			}
		}
	}
	//更新公告
	@Override
	public boolean updateNotice(Notice notice) {
		Transaction ts = null;
		try{
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			ts=session.beginTransaction();
			session.update(notice);
			ts.commit();
			return true;
		}catch(Exception e)
		{
			ts.rollback();
			e.printStackTrace();
            return false;
		}finally{
			if(ts!=null)
			{
				ts=null;
			}
		}
	}
	//按id查找公告
	@Override
	public Notice findNotice(int id) {
		Transaction ts=null;
		String hql="";
		try {
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			ts=session.beginTransaction();
			hql="from Notice where noteId=?";
			Query query=session.createQuery(hql);
			query.setParameter(0, id);
			List<Notice> list=query.list();
			Notice notice=list.get(0);
			ts.commit();
			return notice;
		}catch(Exception e)
		{
			ts.rollback();
			e.printStackTrace();
			return null;
		}finally{
			if(ts!=null)
			{
				ts=null;
			}
		}
	}
	//查找全部公告
	@Override
	public List<Notice> findAllNotice() {
		Transaction ts=null;
		String hql="";
		try {
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			ts=session.beginTransaction();
			hql="from Notice";
			Query query=session.createQuery(hql);
			List<Notice> list=query.list();
			ts.commit();
			return list;
		}catch(Exception e)
		{
			ts.rollback();
			e.printStackTrace();
			return null;
		}finally{
			if(ts!=null)
			{
				ts=null;
			}
		}
	}

}
